﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;

public class AutoUIDir : EditorWindow
{
    static string url_path = "/Scripts/GameScripts/ui/";
    static string proxy_url_path = "/Scripts/GameScripts/proxy";
    static string state_url_path = "/Scripts/GameScripts/fsm/commonState";
    static string className = "";
    static string stateName = "";

    [MenuItem("Tools/自动生成新UI的基础目录以及对应proxy文件")]
    public static void Run()
    {
        EditorWindow.GetWindow(typeof(AutoUIDir), true, "生成目录", true);
    }

    void OnGUI()
    {
        GUILayout.Label("UI目录路径", EditorStyles.boldLabel);
        url_path = EditorGUILayout.TextField("默认路径", url_path);

        GUILayout.Label("proxy目录路径", EditorStyles.boldLabel);
        proxy_url_path = EditorGUILayout.TextField("默认路径", proxy_url_path);

        //GUILayout.Label("类名", EditorStyles.boldLabel);
        className = EditorGUILayout.TextField("类名", className);

        if (GUILayout.Button("开始生成UI目录"))
        {
            ExportAll(1);
        }

        if (GUILayout.Button("开始生成proxy文件"))
        {
            ExportAll(2);
        }

        if (GUILayout.Button("一键生成所有（ui&proxy）"))
        {
            ExportAll(0);
        }

        GUILayout.Label("公用state目录路径", EditorStyles.boldLabel);
        state_url_path = EditorGUILayout.TextField("默认路径", state_url_path);

        stateName = EditorGUILayout.TextField("状态名", stateName);
        if (GUILayout.Button("生成state"))
        {
            ExportState();
        }
    }

    static void ExportState() {
        if (string.IsNullOrEmpty(stateName))
        {
            EditorUtility.DisplayDialog("提示", "stateName IsNullOrEmpty：" + stateName, "了解");
            return;
        }
        string exportState_url_path = Application.dataPath + state_url_path;
        string statePath = exportState_url_path + "/" + string.Format("{0}State.cs", stateName);
        string content =
@"using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class " + stateName + @"State :BaseMajorState<" + stateName + @"State>
{
	public " + stateName + @"State():base(){
		StateID = StateConst." + stateName.Trim().ToLower() + @";
	}

	public override void OnEnter(BaseRoleState role,System.Action endCB=null)
    {
		role." + stateName + @"Enter (endCB);
    }
    public override void OnUpdate(BaseRoleState role)
    {
        role." + stateName + @"Update();
    }
    public override void OnExit(BaseRoleState role)
    {
        role." + stateName + @"Exit();
    }
}
";
        EditorUtility.DisplayProgressBar("生成ing", "生成state" + statePath, 1);
        //不覆盖不重新生成
        if (!File.Exists(statePath)) {
            File.AppendAllText(statePath, content);
        }
        EditorUtility.ClearProgressBar();
    }


    static void ExportAll(int type) {
        if (string.IsNullOrEmpty(className)) {
            EditorUtility.DisplayDialog("提示", "className IsNullOrEmpty：" + className, "了解");
            return;
        }
        string exportProxy_url_path = Application.dataPath + proxy_url_path;

		string exportUrl_path = Application.dataPath + url_path;
        string rootDirName=className[0].ToString().ToLower()+className.Substring(1);//根目录第一个字母小写
		string root = exportUrl_path + rootDirName;
        string viewPath = root + "/view/";
        string viewScriptPath = viewPath + string.Format("{0}View.cs", className);

        string mediatorPath = root + "/mediator/";
        string mediatorScriptPath = mediatorPath + string.Format("{0}Mediator.cs", className);

        string proxyPath = exportProxy_url_path + "/" + string.Format("{0}Proxy.cs", className);

        if ((type==0||type==1)&&  Directory.Exists(root)) {
            //存在的不再创建，不覆盖
            EditorUtility.DisplayDialog("提示", "ui目录已经存在：" + className, "了解");
            return;     
        }

        if ((type == 0 || type == 2) && File.Exists(proxyPath))
        {
            //存在的不再创建，不覆盖
            EditorUtility.DisplayDialog("提示", "proxy文件已经存在：" + className, "了解");
            return;
        }
        bool canUI = false;
        bool canProxy = false;
        if (type == 0) {
            canUI = true;
            canProxy = true;
        }
        else if (type == 1) {
            canUI = true;
        }
        else if (type == 2)
        {
            canProxy = true;
        }
        EditorUtility.DisplayProgressBar("生成ing", "生成目录"+root, 1);
        if (canUI) {
            Directory.CreateDirectory(root);
            if (!Directory.Exists(viewPath))
            {
                Directory.CreateDirectory(viewPath);
            }
            if (!Directory.Exists(mediatorPath))
            {
                Directory.CreateDirectory(mediatorPath);
            }
        }

        //if (!File.Exists(viewScriptPath)) {
        //    File.Create(viewScriptPath);
        //}
        //if (!File.Exists(mediatorScriptPath))
        //{
        //    File.Create(mediatorScriptPath);
        //}

        string viewContent=
@"using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class " +className+ @"View : BaseView { 
    public " + className + @"Proxy proxy = AppFacade.instance.RetrieveProxy(" + className + @") as " + className + @"Proxy;
    public override void InitView(GameObject viewObj, UIManager.DisplayLevel displayLv, UIManager.DestroyType destroyType)
    {
        base.InitView(viewObj,displayLv,destroyType);
        

        AddEvent();
    }

    public override void AddEvent()
    {
        base.AddEvent();
    }


    public override void RemoveEvent()
    {
        base.RemoveEvent();
    }

    public void OnBtnClick(GameObject obj,PointerEventData eventData) {
    
    }

    public override void Hide()
    {
        base.Hide();
    }

    public override void Dispose()
    {
        base.Dispose();

    }
}
";
        if (canUI) {
            File.AppendAllText(viewScriptPath, viewContent);
        }

        string mediatorContent =
@"using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class " +className+ @"Mediator : BaseMediator { 
    //对应子类对象实例，不可用new隐藏，防止影响父类相关函数执行
    new " + className + @"View _viewClass;
    public " + className + @"Mediator(
        string mediatorName,
        /*BaseView viewClass,*/
        string abName,
        string assetName,
        UIManager.DisplayLevel displayLv = UIManager.DisplayLevel.mainview,
        UIManager.DestroyType destroyType = UIManager.DestroyType.IMMEDIATE_DESTROY
        )
    : base(mediatorName, abName, assetName, displayLv, destroyType)
    { 
        
    }

    public override void OnRegister()
    {
        base.OnRegister();
    }

    public override void HandleNotification(PureMVC.Interfaces.INotification notification)
    {
		notificationBody = notification.Body;
        notificationType = notification.Type;
        if (viewClass == null)
        {
            //没有视图 监听到allhide信息则无需处理
            if (notification.Name == AppConst.ALL_HIDE)
            {
                return;
            }
            preNotification = notification;
            MainFacade.instance.CreatePanel(this.abName, this.assetName, LoadViewCallBack,displayLv,destroyType);
            return;
        }
        string notificationName=notification.Name;
        if (notificationName == AppConst.ALL_HIDE) {
            Hide();
        }
        else if (notificationName == AppConst." + className.ToUpper() + @")
        {
            viewClass.Show();
        }
    }

    public override IEnumerable<string> ListNotificationInterests
    {
        get
        {
            return new List<string>() { 
                AppConst.ALL_HIDE,
                AppConst." + className.ToUpper() + @",
            };
        }
    }

    public override void OnRemove()
    {
        base.OnRemove();
    }

	public override void LoadViewCallBack (UnityEngine.Object obj)
	{
        if (viewClass == null) {
		    viewClass = new " + className + @"View ();
            _viewClass= viewClass as " + className + @"View;
		    base.LoadViewCallBack (obj);
        }
	}
}
";
        if (canUI) {
            File.AppendAllText(mediatorScriptPath, mediatorContent);
        }


        string proxyContent =
@"using System.Collections;
using System.Collections.Generic;
using PureMVC.Patterns;
using PureMVC.Interfaces;
using UnityEngine;

public class " +className+@"Proxy: Proxy {

    public " + className + @"Proxy() : base(" + string.Format("\"{0}\"", className) + @") { }

    public override void OnRegister()
    {
        base.OnRegister();
    }

    public override void OnRemove()
    {
        base.OnRemove();
    }
}
";
        if (canProxy) {
            File.AppendAllText(proxyPath, proxyContent);
        }
        AssetDatabase.Refresh();
        EditorUtility.ClearProgressBar();
    }
}
